package ranks.tools.parser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

public class HTMLParser {

	private URLConnection conn;
	private String startPhrase;
	private String endPhrase;
	private Map<String, String> removePhrases;
	
	public HTMLParser(String startPhrase,
					  String endPhrase,
					  Map<String, String> removePhrases) {
		
		this.startPhrase = startPhrase;
		this.endPhrase = endPhrase;
		this.removePhrases = removePhrases;
	}
	
	public String parseURL(String url) {
		String content = "";
		try{
			content = this.parseURL(new URL(url));
		} catch(MalformedURLException mEx) {
			mEx.printStackTrace();
		}
		
		return content;
	}
	
	public String parseURL(URL url) {
		String content = "";
		
		try{
			conn = url.openConnection();
						
			content = parseStream(conn.getInputStream());
		} catch(IOException ioe) {
			ioe.printStackTrace();
		}
		
		return content;
	}
	
	private String parseStream(InputStream stream) throws IOException {
		StringBuffer buffer = new StringBuffer();
		
		BufferedReader reader
			= new BufferedReader(
				new InputStreamReader(stream));
		String line = "";
		boolean writing = false;
		while((line = reader.readLine()) != null) {
			if(line.contains(this.startPhrase)) {
				writing = true;
			}
			if(writing) {
				buffer.append(line + "\n");
			}
			if(line.contains(this.endPhrase)) {
				writing = false;
			}
		}
		
		String content = clearRemovePhrases(buffer.toString());
		
		return content;
	}
	
	private String clearRemovePhrases(final String input) {
		String content = input;
		
		if(this.removePhrases != null) {
			for(String value : this.removePhrases.keySet()) {
				content = content.replaceAll(value, this.removePhrases.get(value));
			}
		}
			
		return content;
	}
	
}
